"use client";

import { createContext, useContext, useState, useEffect } from "react";
import { AuthService } from "@/services/auth.service";
import type { ApiResponse, AuthResponse } from "@/lib/types/api";

interface User {
  _id: string;
  email: string;
  username: string;
  gender?: string;
  description?: string;
  birthdayAt?: Date;
  createdAt: Date;
}

interface AuthContextType {
  user: User | null;
  isLoading: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  register: (data: { email: string; password: string; username: string }) => Promise<void>;
  updateUser?: (data: Partial<User>) => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem("token");
        if (token) {
          const response = await AuthService.getCurrentUser();
          if (response.status && response.data) {
            setUser(response.data as User);
          } else {
            localStorage.removeItem("token");
            localStorage.removeItem("user");
          }
        }
      } catch (error) {
        localStorage.removeItem("token");
        localStorage.removeItem("user");
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, []);

  const login = async (email: string, password: string) => {
    const response = await AuthService.login({ email, password });
    if (response.status && response.data) {
      localStorage.setItem("token", response.data.token);
      setUser(response.data.user as User);
    } else {
      throw new Error(response.message || "登录失败");
    }
  };

  const logout = async () => {
    try {
      await AuthService.logout();
    } catch (error) {
      console.error("Logout failed:", error);
    } finally {
      localStorage.removeItem("token");
      setUser(null);
    }
  };

  const register = async (data: { email: string; password: string; username: string }) => {
    try {
      const response = await AuthService.register(data);
      
      if (!response.status || !response.data) {
        throw new Error(response.message || "注册失败");
      }

      const { token, user: userData } = response.data;
      
      localStorage.setItem("token", token);
      setUser(userData);

    } catch (error) {
      const errorMessage = error instanceof Error 
        ? error.message 
        : "注册过程中发生错误";
      
      console.error('Registration error:', error);
      throw new Error(errorMessage);
    }
  };

  const updateUser = async (data: Partial<User>) => {
    const response = await AuthService.updateUser(data);
    if (response.status && response.data) {
      setUser(response.data as User);
    } else {
      throw new Error(response.message || "更新失败");
    }
  };

  return (
    <AuthContext.Provider value={{ user, isLoading, login, logout, register, updateUser }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}
